package com.zj.core.base

import android.Manifest
import android.annotation.SuppressLint
import android.app.AlertDialog
import android.app.TimePickerDialog
import android.os.Bundle
import android.support.v7.widget.LinearLayoutManager
import android.view.View
import android.widget.LinearLayout
import com.dialogutils.DialogUtils
import com.dialogutils.ToastUtil
import com.fileutils.JsonUtils
import com.fileutils.NumberUtils
import com.fileutils.SPUtils
import com.google.gson.Gson
import com.jniutils.DataCollUtil
import com.systemutils.SoftKeyboardUtils
import com.systemutils.SystemUtil
import com.zj.core.R
import com.zj.core.adapter.RecordListAdapter
import com.zj.core.bean.NurseRecResBean
import com.zj.core.dialog.ListFormDialog
import com.zj.core.tools.Constant
import com.zj.core.ui.RecordActivityUi
import org.jetbrains.anko.setContentView
import kotlin.collections.ArrayList
import com.utils.DateUtils
import com.zj.core.activity.CameraActivity
import com.zj.core.dialog.TemplateChangeDialog
import java.text.SimpleDateFormat
import java.util.regex.Pattern
import com.fileutils.BaseConstant.*
import com.zj.core.dialog.TimeDialog
import com.zj.core.interfaces.RecordListIml
import com.zj.core.interfaces.ResultEmptyIml
import com.zj.core.interfaces.TemplateChangeIml
import com.zj.core.interfaces.TextMessageIml
import com.zj.core.interfaces.annotations.Permissions
import com.zj.core.tools.VoiceFormatTools

open class BaseRecordActivity : BaseNetBeanActivity() {

    private var mLayoutManager: LinearLayoutManager? = null
    private var mRecordAdapter: RecordListAdapter? = null
    private var voiceInputValue = ArrayList<ArrayList<String>>()
    private var mPatternArr: ArrayList<String>? = ArrayList()
    private var mDateFormat: SimpleDateFormat? = null
    private var currentIndex: Int = 0         //需删除元素的下标
    private var mKeyForSP = ""

    var mRecordBean: NurseRecResBean.DatEntity.RowsEntity? = null
    lateinit var view: RecordActivityUi
    var mRecordStatus: Int = 0          //0:新增    1:修改
    var mHospitalStatuStr = ""
    var mGson: Gson? = null
    var mTextSize: Int? = 0
    var mFormListStr = ""
    var saveDialog = 0                 //滑屏退出时的数据状态

    override fun onCreate(groupView: LinearLayout): View? {
        view = RecordActivityUi(groupView)
        return view.setContentView(this)
    }

    @SuppressLint("SimpleDateFormat")
    override fun initView() {
        mDateFormat = SimpleDateFormat("yyyy-MM-dd HH:mm:ss")

        mTextSize = SPUtils.get(BaseApplication.context, Constant.TEXT_SIZE_KEY, 0) as Int
        mRecordBean = intent.getSerializableExtra(Constant.DETAIL_ADD_KEY) as NurseRecResBean.DatEntity.RowsEntity?
        /**
         * 缓存数据KEY
         */
        mKeyForSP = mRecordBean?.id.toString() + mRecordBean?.patientid.toString()
        mRecordStatus = intent.getIntExtra(Constant.DETAIL_ADD_STATUS, 0)

        if (mRecordBean?.msg != null) {
            setTitleText(mRecordBean?.msg!!)                                    //患者备注
        } else {
            setTitleText("数据录入")
        }

        defaultItemValue()

        mGson = Gson()
        with(view) {
            recordCleanView.setOnClickListener(this@BaseRecordActivity)
            recordConnectDevice.setOnClickListener(this@BaseRecordActivity)
            recordCommitBu.setOnClickListener(this@BaseRecordActivity)
        }
        loadVisibility()
    }

    /**
     * 获取到药品列表后加载数据项
     */
    override fun drugsNameResult(mDrugsList: String) {
        mLayoutManager = LinearLayoutManager(this)
        mLayoutManager?.orientation = LinearLayoutManager.VERTICAL

        mRecordAdapter = RecordListAdapter(this, voiceInputValue)
        mRecordAdapter?.apply {
            setAddClickListener(addClickListener)
            setItemTextSize(if (mTextSize == 0) 14 else mTextSize)
            setRecordListListener(listViewIml)
        }
        view.record_scroll.layoutManager = mLayoutManager
        view.record_scroll.adapter = mRecordAdapter
    }

    override fun patternKeyResult(hospitalStatu: String, formList: String) {
        this.mHospitalStatuStr = hospitalStatu
        this.mFormListStr = formList

        var mCacheBuf = ""
        var mTime: String

        cleanPatternArr()
        when {
            mRecordStatus == 1 -> {               //修改
                saveDialog = 1
                if (!mRecordBean?.status.isNullOrBlank()) {
                    addViewData("状态", mRecordBean?.status.toString())
                }
                if (!mRecordBean?.createtime.isNullOrBlank()) {
                    mTime =
                        if (DateUtils.isValidDate(mRecordBean?.createtime, DateUtils.DATE_FORMAT_2)) {           //阿拉伯时间
                            String.format("%1\$tH:%1\$tM", mDateFormat?.parse(mRecordBean?.createtime))
                        } else {
                            mRecordBean?.createtime.toString()
                        }
                    addTimeValue(mTime)
                    whenUpdateMes()
                }
                if (mRecordBean?.measure != "") {
                    addViewData("模板", mRecordBean?.measure?.replace("模板", "").toString())
                }
                if (mRecordBean?.options != "") {
                    updateFormValue(mRecordBean?.options.toString())
                }
                mCacheBuf = mRecordBean?.voice?.replace(":", "")?.replace("\n", "").toString()
            }
            else -> {
                val jsonMap = JsonUtils.getPersonListMap1(getCacheInput())
                for (jsonItem in jsonMap) {
                    when {
                        jsonItem[0] == "时间" -> addTimeValue(jsonItem[1])
                        jsonItem[0] == "表单" -> updateFormValue(jsonItem[1])
                        jsonItem[0].contains("模板") -> addViewData(jsonItem[0], jsonItem[1])
                        else -> mCacheBuf = mCacheBuf + jsonItem[0] + jsonItem[1]
                    }
                }
            }
        }
        patternNomalVoice(mCacheBuf)
        scrollToIndex()
    }

    /**
     * 修改时，状态项时间转换
     */
    private fun whenUpdateMes() {
        if (!mRecordBean?.status.isNullOrBlank()) {
            val mHospitalArray = mHospitalStatuStr.split("|")
            for (mStatusStr in mHospitalArray) {
                if (mRecordBean?.status.toString() == mStatusStr) {
                    if (mStatuMap?.get(mStatusStr) == "1") {     //时间转换
                        timeChange(0)
                    } else {
                        timeChange(1)
                    }
                }
            }
        }
    }

    /**
     * 正文数据项匹配
     */
    fun patternNomalVoice(formatValue: String) {
        var mStatus = false

        val macher = DataCollUtil.getProjectList(PATTERN_SPLITE, formatValue, "$mFormListStr|$mHospitalStatuStr")
        val mHospitalArray = mHospitalStatuStr.split("|")
        for (ObjBean in macher) {
            val surgery = surgeryTime(ObjBean.value)
            val pattern = Pattern.compile("($mFormListStr|$mHospitalStatuStr)").matcher(ObjBean.value)     //匹配内容项目
            if (pattern.find()) {
                for (mStatusStr in mHospitalArray) {
                    if (!surgery.contains("手术日数") &&
                        !surgery.contains("手术后日数") &&
                        pattern.group() == mStatusStr
                    ) {
                        if (mStatuMap?.get(ObjBean.value) == "1") {     //时间转换
                            timeChange(0)
                        } else {
                            timeChange(1)
                        }
                        mPatternArr!!.add("状态|" + ObjBean.value)
                        mStatus = true
                        break
                    }
                }
                if (!mStatus) {
                    mPatternArr!!.add(
                        when {
                            surgery.contains("手术日数") -> "手术日数|${surgery.replace("手术日数", "")}"
                            surgery.contains("手术后日数") -> "手术后日数|${surgery.replace("手术后日数", "")}"
                            else -> pattern.group() + "|" + surgery.replace(pattern.group(), "")
                                .replace("[,|，|。|？|?|！|度]\$".toRegex(), "")
                        }
                    )
                }
                mStatus = false
            }
        }
        for (index in 0 until mPatternArr?.size!!) {
            val mSplit = mPatternArr!![index].split("|")
            checkAddData(mSplit[0], mSplit[1])
        }
        notifyDataChange()
    }

    fun cleanPatternArr() {
        mPatternArr?.clear()
    }

    /**
     * 手术日数转换
     */
    private fun surgeryTime(surgery: String): String {
        with(surgery) {
            when {
                contains("手术艺术") -> return replace("手术艺术", "手术日数")
                contains("手术1术") -> return replace("手术1术", "手术日数")
                contains("手术1出") -> return replace("手术1术", "手术日数")
                contains("手术一术") -> return replace("手术一术", "手术日数")
                contains("手术室术") -> return replace("手术室术", "手术日数")
                contains("手术后入出") -> return replace("手术后入出", "手术后日数")
                contains("手术后置出") -> return replace("手术后置出", "手术后日数")
                contains("手术候日出") -> return replace("手术候日出", "手术后日数")
                contains("手术后出") -> return replace("手术后出", "手术后日数")
                contains("手术后不适出") -> return replace("手术后不适出", "手术后日数")
                contains("手术好日出") -> return replace("手术好日出", "手术后日数")
                contains("手术后1术") -> return replace("手术后1术", "手术后日数")
                contains("手术后一术") -> return replace("手术后一术", "手术后日数")
                contains("手术后艺术") -> return replace("手术后艺术", "手术后日数")
                contains("手术后1出") -> return replace("手术后1出", "手术后日数")
                contains("手术后1竖") -> return replace("手术后1竖", "手术后日数")
                else -> surgery
            }
        }
        return surgery
    }

    /**
     * 时间转换处理
     */
    private fun timeChange(status: Int) {
        when (status) {
            0 -> {                                //阿拉伯数字转汉字形式
                val time = DateUtils.dateFormat(0, getTimeValue(), "").split("|")[0]
                if (getTimeValue() != "" && DateUtils.isValidDate(time, "HH:mm")) {
                    addTimeValue(NumberUtils.ArabDateFormat(time))
                }
            }

            1 -> {                                  //汉字转阿拉伯数字形式
                val time = DateUtils.dateFormat(0, getTimeValue(), "").split("|")[0]
                if (getTimeValue() != "" && DateUtils.isValidDate(time, "HH:mm")) {
                    addTimeValue(NumberUtils.CharDateFormat(time))
                }
            }
        }
    }

    fun checkHospitalStatus(time: String): String {
        return if (mStatuMap?.get(getHospitalStatus()) == "1") {     //时间转换
            NumberUtils.ArabDateFormat(time)
        } else {
            time
        }
    }

    /**
     * 默认数据项
     */
    private fun defaultItemValue() {
        with(ArrayList<String>()) {
            add("时间")
            add("")
            voiceInputValue.add(this)
        }

        with(ArrayList<String>()) {
            add("表单")
            add("")
            voiceInputValue.add(this)
        }
    }

    /**
     * 模板内容修改弹窗
     */
    fun changeDialog(position: Int, mArrItem: ArrayList<String>) {
        TemplateChangeDialog(baseContext)
            .setCallBackIml(templateDialogIml)
            .setDismissIml(object : ResultEmptyIml {
                override fun resultValue() {
                    dialogDismiss()
                }
            })
            .setNurseLevel(mLevelType)
            .setObjList(mFormListStr)
            .setDrugsList(mDrugsList)
            .setTemplateValue(mArrItem)
            .setTemplateIndex(position)
            .show()
    }

    open fun dialogDismiss(){}

    /**
     * 模板项修改回调
     */
    private val templateDialogIml = object : TemplateChangeIml {
        override fun resultTemplateValue(name: String, form: String, index: Int) {
            val titleName = if (name == "诊断模板" || name == "宫缩模板") {
                name.replace("模板", "")
            } else {
                name
            }
            templateStatus(titleName, form, index)
        }
    }

    /**
     * 模板修改
     */
    open fun templateStatus(name: String, form: String, index: Int) {}

    /**
     * 添加一条数据
     */
    private val addClickListener = View.OnClickListener {
        if (view.record_scroll.childCount - 1 == 0) {               //界面没有数据项时直接添加即可
            voiceInputValue.clear()
            addViewData("", "")
            notifyDataChange()
        } else {                                                  //界面有数据时先检查是否存在空白数据项
            checkViewData()
        }
    }

    /**
     * 列表操作回调
     */
    private val listViewIml = object : RecordListIml {
        /**
         * 时间选择提示框
         */
        override fun showTimeDialog() {
            TimeDialog(this@BaseRecordActivity, AlertDialog.THEME_HOLO_LIGHT, mListener)
                .setDialogTitle("时间选择")
                .show()
        }

        /**
         * 删除一条数据
         */
        override fun deleteClick(viewIndex: Int) {
            currentIndex = viewIndex
            showDeleteDialog()
        }

        /**
         * 表单选择提示框
         */
        override fun recheckClick(formStr: String) {
            ListFormDialog(baseContext)
                .setCallBackIml(formListBack)
                .setOldFormStr(formStr.split(","))
                .setFormListValue(formList.split(",") as ArrayList<String>)
                .show()
        }

        /**
         * 录入框改变监听
         */
        override fun editTextChange(viewId: Int, changeStr: String, index: Int) {
            if (voiceInputValue.size - 1 >= index) {
                when (viewId) {
                    0 -> {                                 //标题
                        voiceInputValue[index][0] = changeStr
                    }

                    1 -> {                                 //标题对应值
                        voiceInputValue[index][1] = changeStr
                    }
                }
            }
        }

        /**
         * 模板内容修改弹窗
         */
        override fun showTemplateDialog(position: Int, mArrItem: ArrayList<String>) {
            changeDialog(position, mArrItem)
        }
    }

    /**
     * 时间选择回调
     */
    private val mListener = TimePickerDialog.OnTimeSetListener { _, hourOfDay, minute ->
        val mTimeHour = if (hourOfDay.toString().length == 1) {
            "0$hourOfDay"
        } else {
            "$hourOfDay"
        }

        val timeMinute = if (minute.toString().length == 1) {
            "0$minute"
        } else {
            "$minute"
        }
        addTimeValue(checkHospitalStatus("$mTimeHour:$timeMinute"))
        notifyDataChange()
    }

    /**
     * 表单数据回调
     */
    private val formListBack = object : TextMessageIml {
        override fun messageResult(form: String) {
            voiceInputValue[1][1] = form
            notifyDataChange()
        }
    }

    /**
     * 数据删除提示框
     */
    private fun showDeleteDialog() {
        DialogUtils.create(
            this, null, "是否删除该条数据？", "删除",
            this, "取消", this, true, true,
            false
        ).show()
    }

    override fun onClick(v: View?) {
        when (v?.id) {
            R.id.common_dialog_cancel_tv -> {

            }

            R.id.common_dialog_confirm_tv -> {                   //删除item
                if (voiceInputValue[currentIndex][0] == "状态") {
                    timeChange(1)
                }
                voiceInputValue.removeAt(currentIndex)
                mRecordAdapter?.notifyDataSetChanged()
            }

            R.id.record_clean_view_bu -> {                        //清除输入框
                DialogUtils.create(
                    this, null, "是否清除已录入数据？", "清除",
                    mCleanListener, "取消", mCleanListener, true, true,
                    false
                ).show()
            }

            R.id.record_connect_device -> {                     //设备连接按钮
                connectDevice()
            }

            R.id.record_save_view_bu -> {                       //提交数据
                commitInputValue()
            }

            R.id.base_bar_back_img -> {                //标题栏返回键
                if (mRecordStatus != 1) {              //非修改状态
                    exitView()
                } else {                                 //修改状态
                    saveDialog = 1
                    finish()
                }
            }
        }
    }

    /**
     * 退出当前界面
     */
    private fun exitView() {
        val mListValue = getAllListValue()
        if (mListValue.size > 0) {
            if ((mListValue.size == 2) && (mListValue[0][0] == "时间") && (mListValue[1][0] == "表单")) {
                if ((mListValue[0][1] == "") && (mListValue[1][1] == "")) {
                    saveDialog = 0
                    cacheInputData("")
                    finish()
                } else {
                    loadHintDialog()
                }
            } else {
                loadHintDialog()
            }
        } else {
            saveDialog = 1
            cacheInputData("")
            finish()
        }
    }

    /**
     * 警告提示框
     */
    private fun loadHintDialog() {
        DialogUtils.create(
            this, null, "存在录入数据，是否保存退出？", "确认",
            mExitBuListener, "不保存", mExitBuListener, true, true,
            false, onDismissIml
        ).show()
    }

    /**
     * 数据保存提示框消失监听
     */
    private val onDismissIml = DialogUtils.DismissListener { saveDialog = 0 }

    /**
     * 退出事件监听
     */
    private val mExitBuListener = View.OnClickListener { v ->
        when (v.id) {
            R.id.common_dialog_cancel_tv -> {
                cacheInputData("")
            }

            R.id.common_dialog_confirm_tv -> {
                cacheInputData(mGson?.toJson(getAllListValue())!!)
            }
        }
        saveDialog = 1
        setResult(Constant.RESULT_RECORD_SKY)
        finish()
    }

    /**
     * 左键进入相机界面
     */
    override fun leftClick() {
        if (!SoftKeyboardUtils.hideSoftKeyBoard(this, currentFocus.windowToken)) {
            activityJumpForResult(this, Constant.REQUEST_CAMERA_KEY, CameraActivity().javaClass, Bundle())
        }
    }

    /**
     * 中间按键扫描二维码
     */
    @Permissions(value = [
        Manifest.permission.ACCESS_COARSE_LOCATION,
        Manifest.permission.ACCESS_FINE_LOCATION])
    override fun centerClick() {
        connectDevice()
    }

    /**
     * 设备连接
     */
    open fun connectDevice() {}

    /**
     * 缓存录入信息
     */
    fun cacheInputData(str: String) {
        SPUtils.put(BaseApplication.context, mKeyForSP, str)
    }

    /**
     * 清除事件监听
     */
    private var mCleanListener: View.OnClickListener = View.OnClickListener { v ->
        when (v.id) {
            R.id.common_dialog_cancel_tv -> {
            }

            R.id.common_dialog_confirm_tv -> {                   //清除所有item
                voiceInputValue.clear()
                defaultItemValue()
                mRecordAdapter?.notifyDataSetChanged()
            }
        }
    }

    /**
     * 获取缓存数据
     */
    private fun getCacheInput(): String {
        return SPUtils.get(BaseApplication.context, mKeyForSP, "") as String
    }

    /**
     * 提交数据
     */
    open fun commitInputValue() {}

    /**
     *检查界面是否存在为空的数据
     */
    private fun checkViewData() {
        for (itemIndex in 0 until voiceInputValue.size) {
            if ((voiceInputValue[itemIndex][0] == "" || voiceInputValue[itemIndex][1] == "") && (itemIndex != 0 && itemIndex != 1)) {    //前两项为时间和表单，不做检查
                ToastUtil.showShort(this, "请完整录入数据后添加下一项")
                break
            } else if (itemIndex == voiceInputValue.size - 1) {        //未存在空白项时添加数据,且刷新界面
                addViewData("", "")
                notifyDataChange()
            }
        }
    }

    /**
     *检查最后一项数据是否为空
     */
    fun checkAddData(title: String, value: String) {
        with(voiceInputValue) {
            if (this.size > 2) {
                for (item in 0 until this.size) {
                    if (this[item][0] == title) {
                        this[item][0] = title
                        updateVoiceValue(item, value)
                        break
                    } else if (item == this.size - 1) {
                        val mDataValue = this[this.size - 1]
                        if (mDataValue.size == 2 && mDataValue[0] == "" && mDataValue[1] == "") {   //最后一项为空
                            this[this.size - 1][0] = title
                            updateVoiceValue(this.size - 1, value)
                        } else {                                                                                //最后一项不为空
                            addViewData(title, getValue(title, value))
                        }
                    }
                }
            } else {
                addViewData(title, getValue(title, value))
            }
        }
    }

    /**
     * 清空界面缓存数据
     */
    fun cleanViewData() {
        voiceInputValue.clear()
    }

    /**
     * 添加一条数据
     */
    private fun addViewData(title: String, value: String) {
        with(ArrayList<String>()) {
            add(title)
            add(value)
            voiceInputValue.add(this)
        }
    }

    /**
     * 更新录入数据
     */
    fun updateVoiceValue(index: Int, valueStr: String) {
        if (voiceInputValue[index][0].contains("模板")) {
            voiceInputValue[index][1] = valueStr
        } else if (voiceInputValue[index][0] == "宫底") {
            voiceInputValue[index][1] = valueStr  //NumberUtils.numberCharArab2CN(valueStr)
        } else {
            voiceInputValue[index][1] = getValue(voiceInputValue[index][0], valueStr)
        }
    }

    private fun getValue(title: String, value: String): String {
        if (title == "宫底") {
            return value
        }
        return VoiceFormatTools.formatVoiceValue(title, VoiceFormatTools.drugFirstSolve(value, mDrugsList))
    }

    /**
     * 更新首行时间项
     */
    fun addTimeValue(timeStr: String) {
        voiceInputValue[0][1] = timeStr
    }

    /**
     * 更新表单选项
     */
    fun updateFormValue(formStr: String) {
        voiceInputValue[1][1] = formStr
    }

    /**
     * 获取首行时间
     */
    fun getTimeValue(): String {
        return voiceInputValue[0][1]
    }

    /**
     * 获取列表所有数据
     */
    fun getAllListValue(): ArrayList<ArrayList<String>> {
        return ArrayList<ArrayList<String>>().apply {
            for (itemValue in 0 until voiceInputValue.size) {
                if (voiceInputValue[itemValue][0] != "") {
                    val mArrItem = ArrayList<String>()
                    mArrItem.add(voiceInputValue[itemValue][0])
                    mArrItem.add(voiceInputValue[itemValue][1])
                    add(mArrItem)
                }
            }
        }
    }

    /**
     * 获取状态项的值
     */
    private fun getHospitalStatus(): String {
        for (status in voiceInputValue) {
            if (status[0] == "状态") {
                return status[1]
            }
        }
        return ""
    }

    /**
     * 数据刷新
     */
    fun notifyDataChange() {
        mRecordAdapter?.notifyDataSetChanged()
    }

    /**
     * 滚动列表到末尾
     */
    fun scrollToIndex() {
        view.record_scroll.scrollToPosition(voiceInputValue.size)
    }

    /**
     * 设备按钮的显示状态
     */
    private fun loadVisibility() {
        if (SystemUtil.getSystemModel().contains(PHONE_NAME_VERSION_1)) {
            view.recordConnectDevice.visibility = View.GONE
        }

        if (SystemUtil.getSystemModel().contains(PHONE_NAME_VERSION_2)
            || SystemUtil.getSystemModel().contains(PHONE_NAME_VERSION_3)
        ) {
            view.recordConnectDevice.visibility = View.VISIBLE
        }
    }

    override fun onDestroy() {
        super.onDestroy()
        if (mRecordAdapter != null) {
            mRecordAdapter = null
        }

        if (mLayoutManager != null) {
            mLayoutManager = null
        }
    }
}
